import jwt from 'jsonwebtoken';

// users hardcoded for simplicity, store in a db for production applications
const users = [{ id: 1, username: 'test', password: 'test', firstName: 'Test', lastName: 'User' }]

export default {
    authenticate,
    getAll
}

async function authenticate({ name: username, pwd: password }) {
    const user = users.find(u => u.username === username && u.password === password)

    if (!user) throw '用户名或密码错误'

    const secret = process.env.TOKEN_SECRET
    // create a jwt token that is valid for 7 days
    const token = jwt.sign({ sub: user.id }, secret, { expiresIn: '7d' })

    return {
      data: {
        ...omitPassword(user),
        token
      },
      code: '000000'
    }
}

async function getAll() {
    return users.map(u => omitPassword(u))
}

// helper functions

function omitPassword(user) {
    const { password, ...userWithoutPassword } = user
    return userWithoutPassword;
}